package com.group3.controller;

import com.group3.Feign.ProductServiceFeign;
import com.group3.Feign.CacheServiceFeign;

import com.group3.common.message.SeckillOrderMessage;
import com.group3.common.result.ApiResponse;
import com.group3.common.topic.LiveTopic;
import com.group3.common.topic.SeckillTopic;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/live/mq")
public class MqLiveController {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private ProductServiceFeign productServiceFeign;

    @Autowired
    private CacheServiceFeign cacheServiceFeign;
    // 触发秒杀活动开始消息
    @PostMapping("/startSeckill")
    public ApiResponse startSeckill(@RequestParam String activityId) {
        rocketMQTemplate.convertAndSend(LiveTopic.LIVE_SECKILL_START, activityId);
        return ApiResponse.success("秒杀活动已启动");
    }
    // 秒杀下单接口
    @RequestMapping("/seckill/doSeckill")
    public ApiResponse doSeckill(@RequestParam Integer uid, @RequestParam Integer pid) {
        // 1. 校验用户是否重复秒杀（示例使用内存判断，实际应使用Redis）
        ApiResponse<Boolean> repeatedResp = cacheServiceFeign.repeatedSeckill(uid, pid);
        if (repeatedResp.getData() != null && repeatedResp.getData()) {
            return ApiResponse.error("不能重复参与秒杀");
        }

        // 2. 检测本地库存标识（防止库存不足时继续请求）
        ApiResponse<Boolean> stockOverResp = cacheServiceFeign.isStockOver(pid);
        if (stockOverResp.getData() != null && stockOverResp.getData()) {
            return ApiResponse.error("库存已售罄");
        }


        // 3. 预扣库存（示例使用内存扣减，实际应使用Redis）
        boolean preDecrease = productServiceFeign.decreaseStock(pid, 1);
        if (!preDecrease) {
            cacheServiceFeign.markStockOver(pid);
            return  ApiResponse.error("库存不足");
        }

        // 4. 发送MQ消息异步处理订单
        SeckillOrderMessage message = new SeckillOrderMessage();
        message.setUid(uid);
        message.setPid(pid);
        rocketMQTemplate.syncSend(SeckillTopic.SECKILL_ORDER_CREATE, message);
        return ApiResponse.success("商品正在抢购中，请稍后");
    }



}